package com.conceal.client.controller;

import com.conceal.client.bean.ConcealWxChatCount;
import com.conceal.client.bean.ConcealWxOnlineMatching;
import com.conceal.client.service.ConcealWxChatCountService;
import com.conceal.client.service.ConcealWxOnlineMatchingService;
import com.conceal.client.service.ConcealWxSessionService;
import com.conceal.client.utils.JsonResponse;
import com.conceal.client.utils.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 *conceal  微信小程序controller
 */
@Controller
@RequestMapping("/wx-conceal")
public class WxController {

    private static final String AppID="wx2dfc2ddc9994f7f5";

    private static final  String AppSecret="2d7bcb46ed58ecb5de894a0c779177b9";
    private static final int wxa_session_timeout=18000;//会话超时时间设置
    @Autowired
    private ConcealWxSessionService concealwxSessionService;
    @Autowired
    ConcealWxOnlineMatchingService concealWxOnlineMatchingService;
    @Autowired
    ConcealWxChatCountService concealWxChatCountService;
    
    
    
    @RequestMapping("/login")
    @ResponseBody
    public String  login(String code, String nickName, String avatar,String country,Integer gender,String language,String city,String province ){
        JsonResponse ret = new JsonResponse();
        String sid =  concealwxSessionService.verify(AppID,AppSecret,code,nickName,avatar,country,gender,language,city,province);
        if (sid != null) {
            ret.setResultCode(0);
            ret.setData(sid);
        } else {
            ret.setResultCode(-1);
        }
        return SpringUtil.ObjectToJson(ret);
    }
    
    /**
     * 客户端发起开始匹配请求
     * @param sid
     * @return
     */
    @RequestMapping(value="send-matching-request", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String sendMatchingRequest(String sid) {
    	JsonResponse net = new JsonResponse();
    	if(concealwxSessionService.validateSession(sid, wxa_session_timeout)) {
    		net.setResultCode(0);
    		String pid = concealwxSessionService.getPid(sid, wxa_session_timeout);
    		if(pid!=null) {
    			//调用函数执行
    			Integer match = concealWxOnlineMatchingService.matching(pid);
    			if(match>0) {
    				//查找匹配对象，并发送一条匹配成功指令给用户
    				String targetPid = concealWxChatCountService.selectRecord(pid);
    				System.out.println("targetPid=======================>>>>>>>"+targetPid);
    				WxWebSocket.onSend(targetPid, "1,匹配成功");
    			}
    			net.setData("match",match);
    		}
    	}else {
    		net.setResultCode(-1);
    	}
    	
    	return SpringUtil.ObjectToJson(net);
    }

}
